<template>
  <!-- FBA差异-FBA货件 -->
  <div class="fba-diff-wrap table-gl-w">
    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #tableBody>
          <a-table
            class="table-singe-line show-border-table"
            ref="tableRef"
            row-key="id"
            :loading="tableLoading"
            :data="tableList"
            :summary="isSummary"
            :scroll="{
              x: '100%',
              y: '100%',
            }"
            size="mini"
            @sorter-change="sorterChange"
            :pagination="false"
          >
            <template #columns>
              <a-table-column data-index="sort" title="序号" :width="45" fixed="left">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="shopName" title="店铺" :width="100" fixed="left">
                <template #cell="{ record }">
                  <TextLimit>{{ record.shopName }}</TextLimit>
                </template>
              </a-table-column>
              <a-table-column data-index="shipmentId" title="FBA货件号" :width="100" fixed="left">
                <template #cell="{ record }">
                  <p class="highlight cursor" @click="toDetail(record)">{{ record.shipmentId }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="billNo" title="发货单号" :width="90" fixed="left" />
              <a-table-column data-index="centerId" title="CenterId" :width="100" />
              <a-table-column data-index="skuNum" title="SKU数量" :width="70" />
              <a-table-column data-index="realNum" title="发货数" :width="70" />
              <a-table-column data-index="receiveNum" title="已入库数" :width="70" />
              <a-table-column data-index="differentNum" title="差异" :sortable="sortable" :width="70" />
              <a-table-column data-index="shipFee" title="运费" :width="90" key="shipFee">
                <template #cell="{ record }">
                  <p>￥{{ record.shipFee }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="laborCost" title="处理费" :width="90">
                <template #cell="{ record }">
                  <p>￥{{ record.laborCost }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="productValue" title="产品货值" :sortable="sortable" :width="90">
                <template #cell="{ record }">
                  <p>￥{{ record.productValue }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="packagingValue" title="包装货值" :sortable="sortable" :width="90">
                <template #cell="{ record }">
                  <p>￥{{ record.packagingValue }}</p>
                </template>
              </a-table-column>
              <a-table-column title="提交日期" :width="130" :sortable="sortable">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtSubmit, 'YYYY/MM/DD HH:mm') }}</p>
                </template>
              </a-table-column>
              <a-table-column title="发货日期" :width="130" :sortable="sortable">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtShipped, 'YYYY/MM/DD HH:mm') }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="gmtReceive" title="收货日期（市场）" :sortable="sortable" :width="140" />
            </template>
            <template #summary-cell="{ column }">
              <p v-if="column.dataIndex == 'sort'">合计</p>
              <p v-else-if="['productValue', 'receiveValue', 'packagingValue', 'shipFee', 'laborCost'].includes(column.dataIndex)">￥{{ sumMap[column.dataIndex] }}</p>
              <p v-else>{{ sumMap[column.dataIndex] }}</p>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { FilterTableItem } from '@/types/components'
  import TableWrap from '@/components/TableWrap.vue'
  import { findFbaShipmentDifferentPage, findFbaShipmentDifferentSum } from '@/api/purchase'
  import useBaseDataStore from '@/store/modules/base-data'
  import { getStartAndEndTime } from '@/utils/timeFormat'
  onMounted(() => {
    getShopList()
    getTableList()
  })
  const emit = defineEmits(['changeTab'])

  const defaultTimes = getStartAndEndTime('last_30_days', 'YYYY-MM-DD HH:mm:ss')
  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'shopIds',
      label: '店铺',
      value: ref(),
      type: 'select_multiple',
      width: 200,
      optionItems: [],
    },
    {
      type: 'input_keyword',
      key: 'shipmentIds',
      keyItems: [
        { label: '货件号', value: 'shipmentIds' },
        { label: '发货单号', value: 'billNos' },
      ],
      keyWidth: '110',
      value: ref(),
      placeholder: '请输入',
      label: '货件号',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'keyword_date_range',
      key: 'gmtShipped',
      keyItems: [
        { label: '发货日期', value: 'gmtShipped' },
        { label: '收货日期', value: 'gmtReceive' },
        { label: '提交日期', value: 'gmtSubmit' },
      ],
      keyWidth: '100',
      value: ref(defaultTimes),
      placeholder: '请输入',
      label: '发货日期',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])

  const total = ref(0)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const tableRef = ref()
  const filterData = ref<any>({
    dataType: 'gmtShipped',
    startDate: defaultTimes?.[0],
    endDate: defaultTimes?.[1],
  })
  const useBaseData = useBaseDataStore()
  const searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
  })
  const sumMap = ref<any>({})
  const isSummary = ref(false)
  const sortable: any = ref({
    sortDirections: ['descend', 'ascend'],
    sorter: true,
  })
  // 详情
  function toDetail(item: any) {
    emit('changeTab', {
      tabName: 'fbaItem',
      searchVal: {
        shipmentIds: item.shipmentId,
      },
    })
  }
  // 获取店铺
  async function getShopList() {
    await useBaseData.getShopList()
    filterItem.value[0].optionItems = useBaseData.shopList.map((el: any) => {
      return {
        label: el.shopName,
        value: el.sellerMarketId,
      }
    })
  }
  // 排序
  function sorterChange(dataIndex: string, direction: string) {
    searchVal.value.sortField = dataIndex
    searchVal.value.sortType = direction == 'ascend' ? 1 : -1
    getTableList()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }

  // 通过条件查询用户列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }

  // 获取商品列表
  async function getTableList() {
    let params = {
      ...searchVal.value,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await findFbaShipmentDifferentPage(params)
    tableLoading.value = false
    tableList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
    let shopIds = filterData.value.shopIds
    // 单选店铺合计
    if (shopIds && shopIds?.split(',')?.length === 1) {
      isSummary.value = true
      getSum(params)
    } else {
      isSummary.value = false
    }
  }
  async function getSum(info: any) {
    const res: any = await findFbaShipmentDifferentSum(info)
    sumMap.value = res?.data || {}
  }
</script>
<style lang="less" scoped>
  .fba-diff-wrap {
    height: calc(100vh - @menuAndTabHeight);
  }
</style>
